package com.sun.controller;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.PushGateway;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Counter：只可增加计数器
 * Gauge：可增可减仪表盘
 * Summary：摘要
 * Histogram：直方图
 */
@RestController
public class PrometheusController {

    // 普罗米修斯网关地址：localhost:9091
    // 模拟推送本地地址：localhost:8080
    private static final String PUSH_GATEWAY_RUL = "localhost:9091";

    /**
     * 模拟PushGateway接收数据
     */
    @RequestMapping(value = "/metrics/**", method = RequestMethod.POST,
            consumes = "text/plain")
    public String receiveData(HttpServletRequest request) throws IOException {
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("requestURL = " + requestURL);

        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int length;
        while ((length = inputStream.read(bytes)) != -1) {
            String metrics = new String(bytes, 0, length);
            System.out.println(metrics);
        }
        return "success";
    }

    /**
     * 模拟客户端推送数据到PushGateway
     */
    @GetMapping("/pushDataToGateway/{type}")
    public String pushDataToGateway(@PathVariable String type) throws Exception {
        if(StringUtils.equals(type, "1")) {
            // 方式1
            build1();
        } else {
            // 方式2
            build2();
        }
        return "success";
    }

    /**
     * Labels = test_cpu_metric{CPU="111", GPU="222", job="sun-job1"}
     * Value = 1.1
     */
    private static void build1() throws IOException {
        // 任务名称
        String job = "sun-job1";
        // 指标名称
        String metric = "test_cpu_metric";
        // 描述
        String help = "CPU Metric Help";
        // 标签
        String[] labelNames = new String[]{ "CPU", "GPU" };
        // 标签值
        String[] labelValues = new String[]{ "111", "222" };

        CollectorRegistry registry = new CollectorRegistry();
        // Gauge：可增可减的仪表盘
        Gauge gauge = Gauge.build()
                .name(metric)
                .help(help)
                .labelNames(labelNames)
                .create();
        gauge.labels(labelValues).set(new BigDecimal("1.1").doubleValue());
        registry.register(gauge);

        PushGateway pushGateway = new PushGateway(PUSH_GATEWAY_RUL);
        pushGateway.pushAdd(registry, job);
    }

    /**
     * Labels = test_memory_metric{Disk="1T", Memory="8GB", cluster_name="SH", instance="10.137.0.1",
     * job="sun-job2", nc_model="PV52P1B1(96C/775G)", nc_num="3"}
     *  Value = 1.2
     */
    private static void build2() throws IOException {
        CollectorRegistry registry = new CollectorRegistry();
        Gauge gauge = Gauge.build("test_memory_metric", "Memory Metric Help")
                .labelNames("Memory", "Disk")
                .create();
        gauge.labels("8GB", "1T").set(new BigDecimal("1.2").doubleValue());
        gauge.register(registry);

        Map<String, String> groupingKey = new HashMap<>();
        groupingKey.put("instance", "10.137.0.1");
        groupingKey.put("cluster_name", "SH");
        groupingKey.put("nc_model", "PV52P1B1(96C/775G)");
        groupingKey.put("nc_num", "3");

        PushGateway pg = new PushGateway(PUSH_GATEWAY_RUL);
        pg.pushAdd(registry, "sun-job2", groupingKey);
    }

}
